constructive algorithms greedy implementation math *2000

Please click on ads to support us..

Python Code:

import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

t = int(input())
ans = []
pow10 = [1]
for _ in range(9):
    pow10.append(10 * pow10[-1])
sp = set(pow10)
inf = pow(10, 9) + 1
for _ in range(t):
    s, n = map(int, input().split())
    ans0, x = [], 10
    while s and n ^ 1:
        while not s % x:
            x *= 10
        ans0.append(x // 10)
        s -= ans0[-1]
        n -= 1
    if n == 1 and s:
        ans0.append(s)
    else:
        for _ in range(n):
            ok = 0
            mi, j = inf, -1
            for i in range(len(ans0)):
                if not ans0[i] in sp:
                    x = pow10[len(str(ans0[i])) - 1]
                    ans0.append(ans0[i] - x)
                    ans0[i] = x
                    ok = 1
                    break
                elif mi > ans0[i] and ans0[i] ^ 1:
                    mi, j = ans0[i], i
            if not ok:
                ans0.append(ans0[j] // 2)
                ans0[j] //= 2
    ans.append(" ".join(map(str, ans0)))
sys.stdout.write("\n".join(ans))

C++ Code:

#include<bits/stdc++.h>
using namespace std;
int s,n,x,T;
int main(){
	scanf("%d",&T);
	while (T--){
		scanf("%d %d",&s,&n);
		for (;--n;s-=x) printf("%d ",x=pow(10,(int)log10(s-n)));
		printf("%d\n",s);
	}
	return 0;
} 
	 	 		 		    		     			  		   	


Comments

Submit
0 Comments
More Questions

363D - Renting Bikes
1198D - Rectangle Painting 1
1023B - Pair of Toys
1725A - Accumulation of Dominoes
1675E - Replace With the Previous Minimize
839A - Arya and Bran
16B - Burglar and Matches
1625B - Elementary Particles
1725G - Garage
1725B - Basketball Together
735A - Ostap and Grasshopper
1183B - Equalize Prices
1481A - Space Navigation
1437B - Reverse Binary Strings
1362B - Johnny and His Hobbies
1299A - Anu Has a Function
1111A - Superhero Transformation
954A - Diagonal Walking
39F - Pacifist frogs
1451C - String Equality
386A - Second-Price Auction
1690E - Price Maximization
282B - Painting Eggs
440A - Forgotten Episode
233B - Non-square Equation
628B - New Skateboard
262B - Roma and Changing Signs
755C - PolandBall and Forest
456B - Fedya and Maths
376B - IOU